package com.shaozi.nc.manage.secretary;

import java.util.List;

import org.apache.log4j.Logger;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.shaozi.common.schedule.DyncQuartzManage;
import com.shaozi.data.mq.business.base.MqQuartzBean;
import com.shaozi.data.mq.business.quartz.impl.QuartzApiJobImpl;
import com.shaozi.lib.manage.ManageBase;
import com.shaozi.lib.throwable.SzException;
import com.shaozi.nc.consts.SCConsts.QuartzKey;
import com.shaozi.nc.data.model.MqApiQuartzModel;
import com.shaozi.nc.data.model.SecretaryApiQuartzLogModel;
import com.shaozi.nc.data.mongodao.SecretaryApiQuartzLogMDao;
import com.shaozi.nc.data.mongodao.SecretaryApiQuartzMDao;
import com.shaozi.nc.mq.quartz.QuartzBeanModelUtil;

/**
 * BeanUtils.getBean("secretaryApiQuartzMgr");
 * 
 * @author brenx
 *
 */
public class SecretaryApiQuartzManage extends ManageBase {

	private Logger logger = Logger.getLogger(SecretaryApiQuartzManage.class);
	@Autowired
	private SecretaryApiQuartzMDao secretaryApiQuartzMDao;
	@Autowired
	private DyncQuartzManage dyncQuartzMgr;
	@Autowired
	private SecretaryApiQuartzLogMDao secretaryApiQuartzLogMDao;

	public SecretaryApiQuartzManage() {

	}

	public List<MqApiQuartzModel> listAll(String companyId) throws SzException {
		return secretaryApiQuartzMDao.listAll(companyId);
	}

	/**
	 * 
	 * @param _id
	 * @param delType
	 * @throws SzException
	 */
	public void delModel(String companyId, String _id, int delType) throws SzException {
		secretaryApiQuartzMDao.delModel(companyId, _id, delType);
	}

	public MqApiQuartzModel getModel(String companyId, String _id) throws SzException {
		return secretaryApiQuartzMDao.getById(companyId, _id);
	}

	public void removeSchedule(String companyId, Integer sourceId, int sourceType, String triggerUserId)
			throws SzException {
		List<MqApiQuartzModel> models = secretaryApiQuartzMDao.getBySource(companyId, sourceId, sourceType,
				triggerUserId);
		if ((models != null) && (!models.isEmpty())) {
			MqApiQuartzModel model = models.get(0);
			removeSchedule(companyId, model);
		}
	}

	public void removeSchedule(String companyId, MqApiQuartzModel model) throws SzException {
		String groupKey = QuartzKey.ApiDelayGroupKey;
		String jobName = model.getTopicName();
		String triggerName = model.getId();
		secretaryApiQuartzMDao.delModel(companyId, model.getId(), MqApiQuartzModel.DelType_Cancel);
		try {
			dyncQuartzMgr.removeJob(groupKey, jobName, groupKey, triggerName);
		} catch (SchedulerException e) {
			logger.info(SzException.getStackMessage(e));
		}
	}

	public void saveAndSchedule(String companyId, MqApiQuartzModel model) throws SzException {
		model.setJobClazzName(QuartzApiJobImpl.class.getName());
		List<MqApiQuartzModel> models = secretaryApiQuartzMDao.getBySource(companyId, model.getSourceId(),
				model.getSourceType(), model.getTriggerUserId());
		if ((models != null) && (!models.isEmpty())) {
			MqApiQuartzModel m = models.get(0);
			model.setId(m.getId());
		}
		secretaryApiQuartzMDao.save(companyId, model);
		schedule(companyId, model);
	}

	public boolean schedule(String companyId, MqApiQuartzModel model) {
		Class jobClazz = null;
		try {
			jobClazz = Class.forName(model.getJobClazzName());
		} catch (ClassNotFoundException e) {
			logger.error(model.getId() + ":" + SzException.getStackMessage(e));
			return false;
		}
		String groupKey = QuartzKey.ApiDelayGroupKey;
		String jobName = model.getTopicName() + "_" + model.getId();
		String triggerName = jobName;
		model.getDataMap().put("_id", model.getId());
		model.getDataMap().put("companyId", companyId);
		try {
			if (dyncQuartzMgr.existTrigger(groupKey, triggerName))
				dyncQuartzMgr.removeJob(groupKey, jobName, groupKey, triggerName);
		} catch (SchedulerException e1) {
			logger.info(SzException.getStackMessage(e1));
		}
		try {
			if (model.getAtTime() != null) {
				dyncQuartzMgr.addJobWithOnce(groupKey, jobName, jobClazz, groupKey, triggerName, model.getAtTime(),
						model.getDataMap());
				return true;
			} else if (StringUtils.isEmpty(model.getPushRegex())) {
				dyncQuartzMgr.addJob(groupKey, jobName, jobClazz, groupKey, triggerName, model.getPushRegex(),
						model.getDataMap());
				return true;
			} else {
				throw new SchedulerException("secretary api quartz not schedule");
			}
		} catch (SchedulerException e) {
			logSchedule(companyId, QuartzBeanModelUtil.modelToBean(model), 0, SzException.getStackMessage(e));
		}
		return false;
	}

	public void logSchedule(String companyId, MqQuartzBean quartzBean, int isSucc, String msg) {
		SecretaryApiQuartzLogModel logModel = new SecretaryApiQuartzLogModel();
		logModel.setApiQuartzId(quartzBean.getId());
		logModel.setAtTime(quartzBean.getAtTime());
		logModel.setDataMap(quartzBean.getDataMap());
		logModel.setJobClazzName(quartzBean.getJobClazzName());
		logModel.setJsonData(quartzBean.getJsonData());
		logModel.setPushRegex(quartzBean.getPushRegex());
		logModel.setTopicName(quartzBean.getTopicName());
		logModel.setIsSucc(isSucc);
		logModel.setMsg(msg);
		try {
			secretaryApiQuartzLogMDao.save(companyId, logModel);
		} catch (SzException e) {
			logger.error(e.getStackMessage());
		}
	}
}
